package com.github.niefy.modules.wxma.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.niefy.common.utils.PageUtils;
import com.github.niefy.common.utils.Query;
import com.github.niefy.modules.wxma.config.WxMaLettuceRedisConfigImpl;
import com.github.niefy.modules.wxma.dao.MaAccountMapper;
import com.github.niefy.modules.wxma.entity.MaAccount;
import com.github.niefy.modules.wxma.service.MaAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("wxMaAccountService")
public class MaAccountServiceImpl extends ServiceImpl<MaAccountMapper, MaAccount> implements MaAccountService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxMaService wxMaService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        IPage<MaAccount> page = this.page(
                new Query<MaAccount>().getPage(params),
                new QueryWrapper<MaAccount>()
                        .like(StringUtils.hasText(name), "name", name)
        );

        return new PageUtils(page);
    }

    @PostConstruct
    public void loadWxMaConfigStorages(){
        logger.info("加载小程序配置...");
        List<MaAccount> accountList = this.list();
        if (accountList == null || accountList.isEmpty()) {
            logger.info("未读取到小程序配置，请在管理后台添加");
            return;
        }
        logger.info("加载到{}条小程序配置",accountList.size());
        accountList.forEach(this::addAccountToRuntime);
        logger.info("小程序配置加载完成");
    }

    @Override
    public boolean save(MaAccount entity) {
        Assert.notNull(entity,"WxMaAccount不得为空");
        String appid = entity.getAppid();
        if(this.isAccountInRuntime(appid)){ //已有此appid信息，更新
            logger.info("更新小程序配置");
            wxMaService.removeConfig(appid);
            this.addAccountToRuntime(entity);

            return SqlHelper.retBool(this.baseMapper.updateById(entity));
        }else {//已有此appid信息，新增
            logger.info("新增小程序配置");
            this.addAccountToRuntime(entity);

            return SqlHelper.retBool(this.baseMapper.insert(entity));
        }

    }

    @Override
    public boolean removeByIds(Collection<?> idList) {
        Assert.notEmpty(idList,"WxAccount不得为空");

        // 更新wxMpService配置
        logger.info("同步移除公众号配置");
        idList.forEach(id-> wxMaService.removeConfig((String) id));

        return SqlHelper.retBool(this.baseMapper.deleteBatchIds(idList));
    }

    /**
     * 判断当前账号是存在
     * @param appid
     * @return
     */
    private boolean isAccountInRuntime(String appid){
        try {
            return wxMaService.switchover(appid);
        }catch (NullPointerException e){// sdk bug，未添加任何账号时configStorageMap为null会出错
            return false;
        }
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 添加账号到当前程序，如首次添加需初始化configStorageMap
     * @param entity
     */
    private synchronized void addAccountToRuntime(MaAccount entity){
        String appid = entity.getAppid();
        WxMaDefaultConfigImpl config = new WxMaLettuceRedisConfigImpl(stringRedisTemplate);
        config.setAppid(appid);
        config.setSecret(entity.getSecret());
        config.setToken(entity.getToken());
        config.setAesKey(entity.getAesKey());
        config.setMsgDataFormat(entity.getMsgDataFormat());
        try {
            wxMaService.addConfig(appid,config);
        }catch (NullPointerException e){
            logger.info("需初始化configStorageMap...");
            Map<String, WxMaConfig> configStorages = new HashMap<>(4);
            configStorages.put(appid,config);
            wxMaService.setMultiConfigs(configStorages,appid);
        }
    }


}